<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>供应商管理</el-breadcrumb-item>
      <el-breadcrumb-item>供应商产品编辑</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row class="product-detail-title">
      <el-col :span="12">
        <span>{{ detail.name }}【{{ detail.id }}】</span>
        <span class="product-detail-switch">{{ detail.status.name }}</span>
      </el-col>
      <el-col :span="12" style="text-align: right">
        创建人：{{ detail.creator.name }}
      </el-col>
    </el-row>

    <el-card>
      <el-descriptions>
        <el-descriptions-item label="产品编号">{{
          detail.code
        }}</el-descriptions-item>
        <el-descriptions-item label="供应商产品ID">{{
          detail.joint
        }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{
          detail.provider.name
        }}</el-descriptions-item>
        <el-descriptions-item label="有效期"
          >{{ detail.valid }}{{ detail.valid_unit }}</el-descriptions-item
        >
        <el-descriptions-item label="使用范围限制">{{
          detail.area_limit_flag.name
        }}</el-descriptions-item>
        <el-descriptions-item label="限制方式">
          <span>{{ detail.area_limit_way.name }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="使用范围">
          {{ detail.area_limit_name }}
        </el-descriptions-item>
        <el-descriptions-item label="产品说明">{{
          detail.description ? detail.description : '-'
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-row class="z-mr10">
      <el-button
        class="theme-background-color"
        size="medium"
        @click="openSupplierProductEditDialog"
        v-show="detail.status.id != 1"
        >编辑</el-button
      >
      <el-button size="medium" v-if="detail.status.id === 1" @click="disable"
        >关闭</el-button
      >
      <el-button size="medium" v-else @click="enable">开启</el-button>
    </el-row>

    <el-tabs v-model="activeName" class="product-detail-priceTab">
      <el-tab-pane label="定价规则" name="first"></el-tab-pane>
      <el-tab-pane label="操作记录" name="second"></el-tab-pane>
    </el-tabs>

    <!-- 定价规则卡片视图区域 -->
    <el-card v-show="activeName === 'first'">
      <div slot="header">
        <span>定价规则</span>
        <el-button
          type="text"
          style="float: right; padding: 3px 0"
          v-show="detail.status.id != 1"
          @click="openPriceRuleAddDialog"
          >新增定价规则</el-button
        >
      </div>
      <el-table :data="detail.priceRule" border style="width: 100%">
        <el-table-column prop="id" label="定价规则ID" width="180">
        </el-table-column>
        <el-table-column prop="start_time" label="生效日期" width="180">
        </el-table-column>
        <el-table-column prop="end_time" label="失效日期"> </el-table-column>
        <el-table-column prop="price" label="统一价"> </el-table-column>
        <!-- <el-table-column prop="is_diff" label="是否设置差异价">
        </el-table-column> -->
        <el-table-column prop="remark" label="备注"> </el-table-column>
        <el-table-column prop="status.name" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              type="danger"
              v-show="scope.row.status.id == 1 || scope.row.status.id == 2"
              @click="closePriceRule(scope.row.id)"
              >关闭</el-link
            >
            &nbsp;
            <el-link
              type="primary"
              v-show="scope.row.status.id == 1 || scope.row.status.id == 2"
              @click="openPriceRuleEditDialog(scope.row)"
              >编辑</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 操作记录卡片视图区域 -->
    <el-card v-show="activeName === 'second'">
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in logData"
          :key="index"
          :timestamp="item.create_time + '【' + item.operator_name + '】'"
          >{{ item.operation_desc }}
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 新增定价规则弹窗 -->
    <el-dialog
      title="新增定价规则"
      :visible.sync="priceRuleAddDialogVisible"
      width="60%"
      :before-close="priceRuleAddDialogHandleClose"
    >
      <!-- 新增定价规则组件 -->
      <PriceRuleAdd
        ref="priceRuleRef"
        @showPriceRuleData="getPriceRuleData"
      ></PriceRuleAdd>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priceRuleAddDialogVisible = false">取 消</el-button>
        <el-button class="theme-background-color" @click="savePriceRuleData"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑定价规则弹窗 -->
    <PriceRuleEdit
      ref="priceRuleEditRef"
      :priceRuleId="priceRuleId"
      :priceRuleEditDialogVisible.sync="priceRuleEditDialogVisible"
    ></PriceRuleEdit>

    <!-- 编辑供应商产品弹窗 -->
    <el-dialog
      title="编辑供应商产品"
      :visible.sync="supplierProductEditDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 编辑供应商产品组件 -->
      <ProductBaseInfoAdd
        ref="baseInfoRef"
        :supplierProductForm="supplierProductForm"
        @showProductFormData="getProductFormData"
      ></ProductBaseInfoAdd>
      <span slot="footer" class="dialog-footer">
        <el-button @click="supplierProductEditDialogVisible = false"
          >取 消</el-button
        >
        <el-button
          class="theme-background-color"
          @click="saveSupplierProductData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PriceRuleAdd from './PriceRuleAdd.vue'
import ProductBaseInfoAdd from './ProductBaseInfoAdd.vue'
import PriceRuleEdit from './PriceRuleEdit.vue'

export default {
  components: { PriceRuleAdd, ProductBaseInfoAdd, PriceRuleEdit },
  data() {
    return {
      activeName: 'first',
      detail: {
        status: {},
        creator: {},
        provider: {},
        area_limit_flag: {},
        area_limit_way: {}
      },
      logData: [],
      // 控制新增定价规则弹窗的显示与隐藏
      priceRuleAddDialogVisible: false,
      priceRuleForm: {},
      diffData: [],

      // 控制编辑供应商产品弹窗的显示与隐藏
      supplierProductEditDialogVisible: false,
      // 传入弹窗的数据
      supplierProductForm: {},
      // 弹窗返回的数据
      productFormEdit: {},
      priceRuleId: 0,
      // 控制编辑定价规则弹窗的显示与隐藏
      priceRuleEditDialogVisible: false
    }
  },
  created() {
    const id = this.$route.query && this.$route.query.id
    if (parseInt(id) === 0 || isNaN(id)) {
      this.$router.push('/supplier/configure')
      return
    }
    this.getSupplierProductDetail()
  },
  methods: {
    async getSupplierProductDetail() {
      const { data: res } = await this.$http.post(
        '/admin/provider_product/info',
        { id: this.$route.query.id }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.detail = res.data
    },
    openPriceRuleAddDialog() {
      this.priceRuleAddDialogVisible = true
    },
    priceRuleAddDialogHandleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          // 清空校验
          this.$refs.priceRuleRef.resetAllData()
          done()
        })
        .catch((_) => {})
    },
    getPriceRuleData(data) {
      this.priceRuleForm = data
    },
    async savePriceRuleData() {
      const flag = this.$refs.priceRuleRef.validateForm()
      if (!flag) return
      this.$refs.priceRuleRef.validPriceRuleData()

      if (
        this.priceRuleForm.is_diff &&
        this.priceRuleForm.type == 1 &&
        this.priceRuleForm.diff.length === 0
      ) {
        return this.$message.error('请配置差异价规则')
      }
      // console.log(this.priceRuleForm)
      // console.log(this.diffData)
      var postData = Object.assign(this.priceRuleForm, {
        product_id: this.detail.id
      })
      // 向后端发起请求
      const { data: res } = await this.$http.post(
        '/admin/provider_product/addPrice',
        postData
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('新增定价规则成功')
      this.getSupplierProductDetail()
      this.priceRuleAddDialogVisible = false
      this.$refs.priceRuleRef.resetAllData()
    },
    formatData() {
      this.supplierProductForm = {
        id: this.detail.id,
        product_id: this.detail.link_product.id,
        provider_id: this.detail.provider.id,
        joint: this.detail.joint,
        valid: this.detail.valid,
        valid_unit: this.detail.valid_unit,
        area_limit_flag: this.detail.area_limit_flag.id,
        area_limit_way: this.detail.area_limit_way.id,
        range_name: this.detail.area_limit_name,
        area_limit: this.detail.area_limit,
        ranged_desc: this.detail.ranged_desc,
        description: this.detail.description,
        product_name: this.detail.link_product.name
      }
    },
    openSupplierProductEditDialog() {
      this.formatData()
      this.supplierProductEditDialogVisible = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    getProductFormData(data) {
      this.productFormEdit = data
    },
    async saveSupplierProductData() {
      const flag = this.$refs.baseInfoRef.validateForm()
      if (!flag) return
      // 向后端发起请求
      const { data: res } = await this.$http.post(
        '/admin/provider_product/modi',
        this.productFormEdit
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('编辑产品成功')
      this.getSupplierProductDetail()
      this.supplierProductEditDialogVisible = false
      console.log(this.productFormEdit)
    },
    closePriceRule(id) {
      // console.log(this.detail.name)
      // 弹框询问是否关闭定价规则
      this.$prompt('确定关闭定价规则【' + id + '】吗？', '请输入关闭原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入关闭原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post(
            '/admin/provider_product/delPrice',
            {
              id: id,
              reason: value
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('成功关闭')
          this.getSupplierProductDetail()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    openPriceRuleEditDialog(row) {
      this.priceRuleId = Number.parseInt(row.id)
      this.priceRuleEditDialogVisible = true
    },
    async disable() {
      // 弹框询问是否关闭
      this.$prompt(
        '是否确认关闭供应商产品【' + this.detail.name + '】',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          inputPattern: /^(?!.{500}|^\s*$)/g,
          inputErrorMessage: '请输入关闭原因',
          closeOnClickModal: false
        }
      )
        .then(async ({ value }) => {
          console.log(value)
          const { data: res } = await this.$http.post(
            '/admin/provider_product/statusClose',
            {
              id: this.$route.query.id,
              reason: value
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('成功关闭')
          this.getSupplierProductDetail()
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    async enable() {
      // 弹框询问是否启用
      const confirmResult = await this.$confirm('是否确认开启？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post(
        '/admin/provider_product/statusOpen',
        { id: this.$route.query.id }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('开启成功')
      this.getSupplierProductDetail()
    }
  }
}
</script>

<style lang="less" scoped>
.product-detail-title {
  margin: 10px 0;
}
.product-detail-switch {
  color: #009688;
  padding-left: 5px;
  font-weight: bold;
}
.el-form-item {
  margin-bottom: 12px !important;
}
.el-descriptions-item__container {
  text-align: left;
}
/deep/.el-descriptions-item__label {
  font-size: 13px;
  color: #999999;
}
/deep/.el-descriptions-item__content {
  font-size: 13px;
}
.z-mr10 {
  margin-top: 10px;
}
.product-detail-priceTab {
  background-color: #fff;
  margin: 10px 0;
  padding-left: 10px;
}
/deep/.el-tabs__nav-wrap::after {
  height: 0;
  background-color: #fff !important;
}
.dialog-footer {
  text-align: center;
}
.dialog-footer .el-button--small,
.el-button--small.is-round {
  padding: 9px 40px;
}
</style>
